package com.jn.musicdemo.views;

import android.animation.ObjectAnimator;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.jn.musicdemo.R;
import com.jn.musicdemo.event.MusicEvent;
import com.jn.musicdemo.service.CustomService;
import com.jn.musicdemo.widget.CircleImageView;

public class MusicActivity extends AppCompatActivity implements View.OnClickListener {
   private ImageView mLast;
   private ImageView mPlay;
   private ImageView mNext;
   private CircleImageView mIvMusic;
   private boolean mPlaying = true;

   private TextView mSong; // 歌曲名
   private TextView mSinger; // 歌手名
   private TextView mTime; // 显示播放时间
   private SeekBar mSeekBar; // 进度条
   private MyServiceConnection mConnection;
   private CustomService mService; // 音乐服务实例
   private ObjectAnimator animator;
   private Handler mHandler = new Handler(); // 主线程Handler
   private Runnable updateSeekBarRunnable; // 更新SeekBar进度的Runnable

   @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_music);

      // 初始化视图组件
      mSong = findViewById(R.id.m_Sing);
      mSinger = findViewById(R.id.m_Singer);
      mTime = findViewById(R.id.m_Time);
      mSeekBar = findViewById(R.id.m_progress);
      mLast = findViewById(R.id.last);
      mPlay = findViewById(R.id.play);
      mNext = findViewById(R.id.next);
      mIvMusic = findViewById(R.id.iv_music);

      // 设置按钮点击监听器
      mLast.setOnClickListener(this);
      mPlay.setOnClickListener(this);
      mNext.setOnClickListener(this);

      // 创建服务连接
      mConnection = new MyServiceConnection();

      // 绑定音乐服务
      Intent intent = new Intent(this, CustomService.class);
      bindService(intent, mConnection, BIND_AUTO_CREATE);

      // 创建并启动旋转动画
      animator = ObjectAnimator.ofFloat(mIvMusic, "rotation", 0f, 360.0f);
      animator.setDuration(10000); // 动画旋转一周的时间为10秒
      animator.setInterpolator(new LinearInterpolator()); // 线性插值器
      animator.setRepeatCount(-1); // -1表示设置动画无限循环
      animator.start();

      // 初始化更新SeekBar进度的任务
      updateSeekBarRunnable = new Runnable() {
         @Override
         public void run() {
            updateSeekBarProgress();
            mHandler.postDelayed(this, 1000); // 每秒更新一次
         }
      };
   }

   @Override
   public void onClick(View v) {
      sendCommand2(v.getId());
   }

   private void sendCommand2(int id) {
      if (mService == null) {
         return;
      }
      if (id == R.id.last) {
         mService.last();
         if (!mPlaying) {
            mPlay.setImageResource(R.drawable.baseline_pause_circle_outline_24);
            mPlaying = true;
            animator.start();
         }
      } else if (id == R.id.next) {
         mService.next();
         if (!mPlaying) {
            mPlay.setImageResource(R.drawable.baseline_pause_circle_outline_24);
            mPlaying = true;
            animator.start();
         }
      } else if (id == R.id.play) {
         if (mPlaying) {
            mService.pause();
            mPlay.setImageResource(R.drawable.baseline_play_circle_outline_24);
            mPlaying = false;
            animator.pause();
         } else {
            mService.play();
            mPlay.setImageResource(R.drawable.baseline_pause_circle_outline_24);
            mPlaying = true;
            animator.start();
         }
      }
   }

   private class MyServiceConnection implements ServiceConnection {

      @Override
      public void onServiceConnected(ComponentName name, IBinder service) {
         mService = ((CustomService.MyBinder) service).getService();
         // 注册音乐状态改变监听器
         mService.setOnMusicPlayStateChangeListener(new CustomService.OnMusicPlayStateChangeListener() {
            @Override
            public void onMusicInfoChanged(String title, String artist) {
               mSong.setText(title);
               mSinger.setText(artist);
               updateSeekBarProgress(); // 当歌曲信息改变时更新SeekBar
            }

            @Override
            public void onPlayStart() {
               updateSeekBarProgress(); // 当音乐开始播放时更新SeekBar
            }

            @Override
            public void onPlayStop() {
               // 当音乐停止播放时执行的操作
            }

            @Override
            public void onPlayComplete() {
               // 当音乐播放完成时执行的操作
            }

            @Override
            public void onMusicListChanged(Cursor cursor) {
               // 当音乐列表改变时执行的操作
            }
         });

         // 开始播放音乐
         mService.play();

         // 启动更新SeekBar进度的任务
         mHandler.post(updateSeekBarRunnable);
      }

      @Override
      public void onServiceDisconnected(ComponentName name) {
         mService = null;
         mHandler.removeCallbacks(updateSeekBarRunnable);
      }
   }

   // 更新SeekBar进度的方法
   private void updateSeekBarProgress() {
      if (mService != null) {
         int currentPosition = mService.getCurrentPosition();
         int max = mService.getDuration();
         mSeekBar.setMax(max);
         mSeekBar.setProgress(currentPosition);
         // 更新时间显示
         mTime.setText(formatTime(currentPosition) + "/" + formatTime(max));
      }
   }

   // 时间格式化方法
   private String formatTime(int timeInMillis) {
      int totalSeconds = timeInMillis / 1000;
      int seconds = totalSeconds % 60;
      int minutes = totalSeconds / 60;
      return String.format("%02d:%02d", minutes, seconds);
   }

   // 设置SeekBar的onChangeListener以同步进度
   @Override
   protected void onResume() {
      super.onResume();
      mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
         @Override
         public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
               mService.seekTo(progress);

            }
         }

         @Override
         public void onStartTrackingTouch(SeekBar seekBar) {}

         @Override
         public void onStopTrackingTouch(SeekBar seekBar) {}
      });
      // 从Intent中获取传递过来的数据
      Intent intent = getIntent();
      if (intent != null) {
         // 获取歌曲名称
         String songTitle = intent.getStringExtra("title");
         // 获取歌手名称
         String artistName = intent.getStringExtra("artist");

         // 显示接收到的数据
         displayReceivedData(songTitle, artistName);
      }

   }


   // 在onPause或onDestroy中停止更新任务
   @Override
   protected void onPause() {
      super.onPause();
      mHandler.removeCallbacks(updateSeekBarRunnable);
   }

   @Override
   protected void onDestroy() {
      super.onDestroy();
      mHandler.removeCallbacks(updateSeekBarRunnable);
      if (mService != null) {
         unbindService(mConnection);
         mService = null;
      }
      Intent resultIntent = new Intent();
      resultIntent.putExtra("mTitle", mSong.getText().toString());
      resultIntent.putExtra("mArtist", mSinger.getText().toString());
      setResult(RESULT_OK, resultIntent);
   }
   private void displayReceivedData(String title, String artist) {
      mSong.setText(title);
      mSinger.setText(artist);
   }
}